#!/bin/bash
source "`dirname "${0}"`/munkiwebadmin-config"
SUBMITURL="${MWA_HOST}/update"
LOOKUPURL="${MWA_HOST}/lookup/ip"

RUNTYPE="$1"
MAC=`ifconfig en0 | awk '$1=="ether" {print $2}'`
NAME=`/usr/sbin/scutil --get ComputerName`


if [ "$RUNTYPE" == "custom" -o "$RUNTYPE" == "auto" ]; then
    if [ ! -z "$MWA_ALLOWED_NETWORKS" ]; then
        echo "Checking network"
        
        external_ip=`mwa_curl --max-time 5 --fail "${LOOKUPURL}"`
        if [ $? -ne 0 ]; then
            echo "External IP lookup failed, aborting munki run"
            exit 1
        fi
        
        prefix_ok="no"
        for prefix in ${MWA_ALLOWED_NETWORKS[@]}; do
            echo -n "Checking $prefix for IP address $external_ip"
            prefix_len=$( echo `echo "$prefix" | tr . '\012' | wc -l` )
            for (( i=$prefix_len ; i<4 ; i++ )); do
                echo -n '.x'
            done
            my_ip_prefix=`echo $external_ip | cut -d. -f1-$prefix_len`
            if [ "$my_ip_prefix" == "$prefix" ]; then
                echo ": Inside"
                prefix_ok="yes"
                break
            else
                echo ": Outside"
            fi
        done
        if [ "$prefix_ok" == "yes" ]; then
            echo "Network check OK, proceeding with munki run"
        else
            echo "Network check failed, aborting munki run"
            exit 1
        fi
    fi
fi

mwa_curl --max-time 5 \
    -d runtype="$RUNTYPE" \
    -d mac="$MAC" \
    -d name=\""$NAME"\" \
    "$SUBMITURL/preflight"

exit 0
